package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.IotProductVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2025/5/25 14:40
 * @Version 1.0
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class DeviceServiceImpl implements IDeviceService {

    private final IoTDAClient client;
    private final StringRedisTemplate redisTemplate;
    private final DeviceMapper deviceMapper;

    private final static String PRODUCT_LIST_KEY = "iot:product";

    /**
     * 查询产品详情
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        //参数校验
        if(StringUtils.isEmpty(productKey)){
            throw new BaseException("请输入正确的参数");
        }
        //调用华为云物联网接口
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.setProductId(productKey);
        ShowProductResponse response;

        try {
            response = client.showProduct(showProductRequest);
        } catch (Exception e) {
            throw new BaseException("查询产品详情失败");
        }
        //判断是否存在服务数据
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if(CollUtil.isEmpty(serviceCapabilities)){
            return AjaxResult.success(Collections.emptyList());
        }

        return AjaxResult.success(serviceCapabilities);
    }

    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest showDeviceShadowRequest = new ShowDeviceShadowRequest();
        showDeviceShadowRequest.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(showDeviceShadowRequest);

        Map<String,Object> map = (Map<String,Object>)JSONUtil.getByPath(JSONUtil.parse(response), "shadow[0].reported.properties");
        String localDateTime = (String)JSONUtil.getByPath(JSONUtil.parse(response), "shadow[0].reported.eventTime");

        LocalDateTime LdTime =  LocalDateTimeUtil.parse(localDateTime, "yyyyMMdd'T'HHmmss'Z'");
        //日期时区转换
        LocalDateTime eventTime = LdTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        List<Map<String, Object>> list = new ArrayList<>();
        map.forEach((k,v) ->{
            Map<String,Object> oneData = new HashMap<>();
            oneData.put("functionId",k);
            oneData.put("value",v);
            oneData.put("eventTime",eventTime);
            list.add(oneData);
        });

        return list;
    }

    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if(device == null){
            throw new BaseException("设备不存在");
        }
        DeviceDetailVo deviceDetailVo = new DeviceDetailVo();
        BeanUtils.copyProperties(device, deviceDetailVo);
        //IOT数据
        ShowDeviceRequest showDeviceRequest = new ShowDeviceRequest();
        showDeviceRequest.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(showDeviceRequest);
        deviceDetailVo.setDeviceStatus(response.getStatus());  //设置状态
        //激活时间
        String activeTimeStr = response.getActiveTime();
        //注意：有可能没有激活
        if(StringUtils.isNotEmpty(activeTimeStr)) {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            //时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC)).
                    withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();

            deviceDetailVo.setActiveTime(activeTime);
        }

        return deviceDetailVo;
    }

    @Override
    public void syncProductList() {
        log.info("开始同步IOT平台产品列表");
        ListProductsResponse response = client.listProducts(new ListProductsRequest());
        log.info("IOT平台返回：{}",response);
        List<ProductSummary> products = response.getProducts();
        redisTemplate.opsForValue().set(PRODUCT_LIST_KEY, JSONUtil.toJsonStr(products));
    }

    @Override
    public List<IotProductVo> allProduct() {
        String productStr = redisTemplate.opsForValue().get(PRODUCT_LIST_KEY);
        if(StringUtils.isEmpty(productStr)){
            return new ArrayList<>();
        }
        return JSONUtil.toList(productStr, IotProductVo.class);
    }

    /**
     * 查询设备维护列表
     *
     * @param device 设备维护
     * @return 设备维护
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //检查设备名称或者设备标识是否重复
        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Device::getDeviceName, deviceDto.getDeviceName());
        wrapper.or().eq(Device::getNodeId, deviceDto.getNodeId());
        Long existNum = deviceMapper.selectCount(wrapper);
        if(existNum != 0) {
            throw new BaseException("设备名称或者标识重复");
        }
        LambdaQueryWrapper<Device> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Device::getBindingLocation, deviceDto.getBindingLocation());
        wrapper1.eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType());
        wrapper1.eq(Device::getProductKey, deviceDto.getProductKey());
        wrapper1.eq(Device::getLocationType, deviceDto.getLocationType());
        if(deviceMapper.selectCount(wrapper1) > 0){
            throw new BaseException("该位置已绑定该产品，请重新选择");
        }

        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        addDevice.setDeviceName(deviceDto.getDeviceName());
        addDevice.setNodeId(deviceDto.getNodeId());
        addDevice.setProductId(deviceDto.getProductKey());

        //设备秘钥
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        AuthInfo authInfo = new AuthInfo();
        authInfo.setSecret(secret);
        addDevice.setAuthInfo(authInfo);

        addDeviceRequest.setBody(addDevice);

        AddDeviceResponse response = client.addDevice(addDeviceRequest);
        log.info("向IOT平台注册返回：{}",response);

        Device device = new Device();
        BeanUtils.copyProperties(deviceDto, device);
        device.setIotId(response.getDeviceId());
        device.setSecret(secret);
        device.setBindingLocation(deviceDto.getBindingLocation() + "");
        deviceMapper.insert(device);
    }
}